//
//  SetViewContrller.swift
//  OneMeeting
//
//  Created by zhangheng on 2019/8/8.
//  Copyright © 2019 www.zhangheng.com. All rights reserved.
//

import Foundation

class SetViewContrller: BaseViewController {
    
    override func loadView() {
        let view = NSView.init(frame: NSRect.init(x: 0, y: 0, width: kSetWinWidth, height: kSetWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(237).cgColor
        self.view = view
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
        //登录状态
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatus(notification:)), name: MTLoginStateNotification, object: nil)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
        self.reLoadData()
    }
    
    func setupUI()  {
        self.view.addSubview(webview)
        webview.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(NSEdgeInsets.init(top: 0, left: 0, bottom: kTabarHeight, right: 0))
        }
        
        self.view.addSubview(tabarView)
        tabarView.snp.makeConstraints { (make) in
            make.height.equalTo(kTabarHeight)
            make.width.equalToSuperview()
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        self.tabarView.addSubview(backBtn)
        backBtn.snp.makeConstraints { (make) in
            make.height.width.equalTo(18)
            make.centerY.equalToSuperview()
            make.left.equalTo(20)
        }
        
        self.tabarView.addSubview(fowBtn)
        fowBtn.snp.makeConstraints { (make) in
            make.height.width.equalTo(18)
            make.centerY.equalToSuperview()
            make.left.equalTo(backBtn.snp.right).offset(20)
        }
        
        self.tabarView.addSubview(reloadBtn)
        reloadBtn.snp.makeConstraints { (make) in
            make.height.width.equalTo(18)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
    }
    
    func reLoadData()  {
        self.load(url: URL.init(string:mt_url_settings)!)
    }
    
    @objc func backBtnAction() {
        if self.webview.canGoBack == true {
            self.webview.goBack()
        }
    }
    @objc func fowBtnAction() {
        if self.webview.canGoForward == true {
            self.webview.goForward()
        }
    }
    
    @objc func reloadBtnAction() {
        self.webview.reload()
    }
    
    func reloadBtnStatus() {
        let image = self.webview.canGoForward == true ? "ic_forwor":"ic_forwor_clear"
        self.fowBtn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init(image))
        
        let fowimage = self.webview.canGoBack == true ? "ic_back":"ic_back_clear"
        self.backBtn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init(fowimage))
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        self.webview.configuration.userContentController.removeScriptMessageHandler(forName: "refresh")
        self.webview.configuration.userContentController.removeScriptMessageHandler(forName: "liveshare")
        self.webview.configuration.userContentController.removeScriptMessageHandler(forName: "download")
    }
   
    
    lazy var tabarView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(238).cgColor
        return view
    }()
    
    lazy var backBtn: LLCustomBtn = {
        let btn = LLCustomBtn()
        btn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init("ic_back_clear"))
        btn.isHandCursor = true
        btn.action = #selector(backBtnAction)
        btn.target = self
        return btn
    }()
    
    lazy var fowBtn: LLCustomBtn = {
        let btn = LLCustomBtn()
        btn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init("ic_forwor_clear"))
        btn.isHandCursor = true
        btn.action = #selector(fowBtnAction)
        btn.target = self
        return btn
    }()
    
    lazy var reloadBtn: LLCustomBtn = {
        let btn = LLCustomBtn()
        btn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init("ic_refresh"))
        btn.isHandCursor = true
        btn.action = #selector(reloadBtnAction)
        btn.target = self
        return btn
    }()
    
    lazy var webview: WKWebView = {
        let config = WKWebViewConfiguration( )
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        config.preferences = preferences
        let userctrl = WKUserContentController()
        userctrl.add(self, name: "liveState")
        userctrl.add(self, name: "refresh")
        userctrl.add(self, name: "liveshare")
        userctrl.add(self, name: "download")
        config.userContentController = userctrl
        
        let web = WKWebView.init(frame: NSRect.zero, configuration: config)
        web.translatesAutoresizingMaskIntoConstraints = false
        
        web.uiDelegate = self
        web.navigationDelegate = self
        return web
    }()
    
    func load(url:URL) -> () {
        let lang = Localize.currentLanguage() == "zh-Hans" ? "cn":"en"
        let urlstring = "\(mt_url_settings)?ownid=\(UserInfoManager.shared.ownid!)&version=\(AppInfo.majorVersion())&type=mac&lang=\(lang)"
        webview.load(URLRequest.init(url: URL.init(string: urlstring)! ))
    }
    
}
extension SetViewContrller:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler {
   
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //刷新按钮ui
        self.reloadBtnStatus()
        self.dismiss()
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.dismiss()
    }
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.hud()
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //self.webview.reload()
        
        switch message.name {
        case "liveState":
             let dic = message.body as! [String:Any]
             if let isok = dic["isok"] as? Int {
                UserInfoManager.shared.isOnLive = (isok==0) ? false:true
             }
        case "refresh":
            self.view.makeToast(message: "设置已改变".localized(),isImage:true)
            NotificationCenter.default.post(name: MTSetChangeNotification, object: nil)
        case "liveShare":
            //self.view.makeToast(message: "设置已改变".localized(),isImage:true)
            let dic = message.body as! [String:Any]
            print("直播分享url = \(dic["url"] as! String)title: \(dic["title"] as! String)")
        case "download":
            let dic = message.body as! [String:Any]
            print("download url = \(dic["url"] as! String))")
        case "Share":
            let dic = message.body as! [String:Any]
            print("download url = \(dic["url"] as! String))")
        default:
            break
        }
    }
}

extension SetViewContrller {
    @objc func loginStatus(notification:Notification) {
        self.reLoadData()
    }
}
